<template>
  <view class="content">
    <view class="padding-top-xl bg-blue"></view>

    <scroll-view
      scroll-y="true"
      :style="scrollHeight"
      :scroll-top="scrollTop"
    >
      <view v-for="(item, index) in list" :key="index" class="cu-chat">
        <view class="cu-item self" v-if="item.flag==0">
					<view class="main">
						<view class="content bg-green shadow">
							<text>{{item.msg}}</text>
						</view>
					</view>
					<view class="cu-avatar radius">
            <view class="cu-avatar radius">
              <image style="width:40px;height:40px;" :src="userImg"></image>
					  </view>
					</view>
					<view class="date">{{item.time}}</view>
				</view>

				<view class="cu-item"  v-if="item.flag==1">
					<view class="cu-avatar radius">
              <image style="width:40px;height:40px;" src="../../static/cat.jpeg"></image>
					</view>
					<view class="main">
						<view class="content shadow">
							<text>{{item.msg}}</text>
						</view>
					</view>
					<view class="date ">{{item.time}}</view>
				</view>
      </view>
    </scroll-view>
    <!-- 发送 -->
    <view class="send">
      <view class="send_box">
        <view class="input"
          ><input
            type="text"
            placeholder="请输入要发送的内容"
            v-model="values"
            cursor-spacing="10"
          />
        </view>
        <view class="btn" @tap="send()">发送</view>
      </view>
    </view>
  </view>
</template>

<script>
import IM from "../../components/IM.js/im.js";
import dataJson from "./data"
export default {
  data() {
    return {
      /*聊天信息*/
      list: [],
      /*发送内容*/
      values: "",
      /*滚动距离*/
      scrollTop: 0
    };
  },
  computed:{
    scrollHeight() {
      var height = uni.getSystemInfoSync() ? uni.getSystemInfoSync().windowHeight : ''
      return `height:${height-55}px`
    },
    userImg(){
      if (this.$store.state.user) {
        return JSON.parse(this.$store.state.user.userInfo).photoUrl
      }else{
        return ""
      }
    }
  },
  created() {
    // this.checkOpenSocket(); 
  },
  // 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
  beforeDestroy() {
    this.closeSocket();
  },
  mounted() {
    wx.onSocketOpen(function(res) {
          console.log("打开");
          
        })
  },
  methods: {
    /*发送消息*/
    send() {
      if (this.values) {
        let obj = {
          msg:this.values,
          time:this.getTime(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss'),
          flag:0
        }
        this.values=""
        this.list.push(obj)
        this.$nextTick(()=>{
          this.scrollTop = this.list.length * 100
        })
        console.log(dataJson);
        setTimeout(() => {
          let toMsg = dataJson.filter(val=>{
          return val.from.indexOf(obj.msg)!=-1
          })
          console.log(toMsg);
          if (toMsg.length!=0) {
            var toObj={
              msg: toMsg[0].to,
              time:this.getTime(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss'),
              flag:1
            }
            this.list.push(toObj)
          }else{
            var toObj={
              msg: "没太明白您的问题，您可以详细说一下嘛？",
              time:this.getTime(new Date().getTime(), 'yyyy-MM-dd HH:mm:ss'),
              flag:1
            }
            this.list.push(toObj)
          }
          this.$nextTick(()=>{
            this.scrollTop = this.list.length * 100
          })
        }, 2000);
        
        // 注：只有连接正常打开中，才能正常成功发送消息
        // var message = {
        //    deleverType: 0X10,
        //     fromAccount:'lh123',
        //     messageType: 0X01,
        //     msg:'你好！！',
        //     toAccount:'li0117'
        // }; //json格式要发送的消息
        // wx.onSocketOpen(function(res) {
        //   console.log('WebSocket连接已打开！');
        //   wx.sendSocketMessage({
        //     data: JSON.stringify(message),
        //     success(res) {
        //       console.log(res + "消息发送成功");
        //     },
        //     fail: (err) => { // 未连接打开websocket连接
        //       console.log(err,'发送失败，未连接websoket，重新链接中');
        //       this.connectSocketInit(); 
        //     }
        //   });
        // })
      }else{
        uni.showToast({
          title: "不允许发送空白信息",
          icon: "none"
        });
      }
    },

    // 判断是否已连接
	    checkOpenSocket () {
				let self = this;
				uni.sendSocketMessage({
					 data: 'ping',
					 success: (res) => {
						return;
					},
					fail: (err) => { // 未连接打开websocket连接
						self.connectSocketInit(); 
					}
				});
			},

    connectSocketInit() {
      wx.connectSocket({
        url: "wss://www.slowcommunity.top/chat/socket/lh123/lh123",   //ws协议链接地址
        header:{
          'content-type': 'application/json'
        },
        method:"POST",
        success(res) {
          console.log(res,"websocket创建成功");
        },
        fail(err){
          console.log('创建失败',err);
        }
      });
      wx.onSocketOpen(function(res) {
        console.log("打开");
      })
      wx.onSocketError(function(err){
        console.log(err,999999);
      })
    },

    // 关闭websocket
    closeSocket() {
      wx.closeSocket({
        success(res) {
          console.log("关闭成功", res);
        },
        fail(err) {
          console.log("关闭失败", err);
        }
      });
    },
    getTime(time, format) {
				var t = new Date(time);
				var tf = function(i) {
					return (i < 10 ? '0' : '') + i
				};
				return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
					switch (a) {
						case 'yyyy':
							return tf(t.getFullYear());
							break;
						case 'MM':
							return tf(t.getMonth() + 1);
							break;
						case 'mm':
							return tf(t.getMinutes());
							break;
						case 'dd':
							return tf(t.getDate());
							break;
						case 'HH':
							return tf(t.getHours());
							break;
						case 'ss':
							return tf(t.getSeconds());
							break;
					}
				})
			}
  }
};
</script>

<style lang="scss">
.cu-chat {
	display: flex;
	flex-direction: column;
}

.cu-chat .cu-item {
	display: flex;
	padding: 30upx 30upx 70upx;
	position: relative;
}

.cu-chat .cu-item>.cu-avatar {
	width: 80upx;
	height: 80upx;
}

.cu-chat .cu-item>.main {
	max-width: calc(100% - 260upx);
	margin: 0 40upx;
	display: flex;
	align-items: center;
}

.cu-chat .cu-item>image {
	height: 320upx;
}

.cu-chat .cu-item>.main .content {
	padding: 20upx;
	border-radius: 6upx;
	display: inline-flex;
	max-width: 100%;
	align-items: center;
	font-size: 30upx;
	position: relative;
	min-height: 80upx;
	line-height: 40upx;
	text-align: left;
}

.cu-chat .cu-item>.main .content:not([class*="bg-"]) {
	background-color: #ffffff;
	color: #333333;
}

.cu-chat .cu-item .date {
	position: absolute;
	font-size: 24upx;
	color: #8799a3;
	width: calc(100% - 320upx);
	bottom: 20upx;
	left: 160upx;
}

.cu-chat .cu-item .action {
	padding: 0 30upx;
	display: flex;
	align-items: center;
}
.cu-chat .cu-item .main .bg-green{
  background-color: #39b54a;
	color: #ffffff;
}

.cu-chat .cu-item>.main .content::after {
	content: "";
	top: 27upx;
	transform: rotate(45deg);
	position: absolute;
	z-index: 100;
	display: inline-block;
	overflow: hidden;
	width: 24upx;
	height: 24upx;
	left: -12upx;
	right: initial;
	background-color: inherit;
}

.cu-chat .cu-item.self>.main .content::after {
	left: auto;
	right: -12upx;
}

.cu-chat .cu-item>.main .content::before {
	content: "";
	top: 30upx;
	transform: rotate(45deg);
	position: absolute;
	z-index: -1;
	display: inline-block;
	overflow: hidden;
	width: 24upx;
	height: 24upx;
	left: -12upx;
	right: initial;
	background-color: inherit;
	filter: blur(5upx);
	opacity: 0.3;
}

.cu-chat .cu-item>.main .content:not([class*="bg-"])::before {
	background-color: #333333;
	opacity: 0.1;
}

.cu-chat .cu-item.self>.main .content::before {
	left: auto;
	right: -12upx;
}

.cu-chat .cu-item.self {
	justify-content: flex-end;
	text-align: right;
}

.cu-chat .cu-info {
	display: inline-block;
	margin: 20upx auto;
	font-size: 24upx;
	padding: 8upx 12upx;
	background-color: rgba(0, 0, 0, 0.2);
	border-radius: 6upx;
	color: #ffffff;
	max-width: 400upx;
	line-height: 1.4;
}
.send {
  background-color: white;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  border-top: 1px solid #dfdfdf;
  padding: 20rpx 20rpx 20rpx 20rpx;

  .send_box {
    display: flex;
    justify-content: space-around;
    align-items: center;

    image {
      width: 48rpx;
      height: 48rpx;
    }
  }

  .input {
    border-bottom: 1px solid #dfdfdf;
    width: 64%;
    padding: 10rpx 0;
  }

  .btn {
    width: 16%;
    background-color: #1d8bf8;
    color: white;
    text-align: center;
    padding: 12rpx 0;
    border-radius: 8rpx;
  }
}
.content{
  width: 100%;
  height: 100%;
  background: #f1f1f1;
}

.left,
.right {
  image {
    width: 100rpx;
    height: 100rpx;
  }
}
</style>
